package com.citycloud.ccuap.tc.oauth2.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.citycloud.ccuap.commons.sys.entity.SysUser;
import com.citycloud.ccuap.tc.common.dto.DataCSecurityBasicUser;
import com.citycloud.ccuap.tc.oauth2.service.UserService;
import com.google.common.collect.Lists;

/**
 * 自定义用户认证与授权
 * <p>
 * Description:
 * </p>
 *
 * @author zhangxu
 * @version v1.0.0
 * @date 2019-04-04 23:57:04
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    private static final String ADMIN_USER_NO = "admin";
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.getByUsername(username);

        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (user != null) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ADMIN");
            grantedAuthorities.add(grantedAuthority);
            if(ADMIN_USER_NO.equals(user.getUserNo())){
                grantedAuthority = new SimpleGrantedAuthority("ROLE_SUPER_USER");
                grantedAuthorities.add(grantedAuthority);
            }

            DataCSecurityBasicUser basicUser = new DataCSecurityBasicUser(String.valueOf(user.getUserNo()), passwordEncoder.encode(user.getPassword()), (user.getDataStatus() != null && user.getDataStatus() == 1) ? true : false, grantedAuthorities);
            basicUser.setUserId(user.getUserId());
            basicUser.setUserName(user.getUserName());
            // 判断是否为平台管理员
            basicUser.setPlatformManager(userService.isPlatformManager(user.getUserId()));
            return basicUser;
        } else {
            throw new UsernameNotFoundException("Username " + username + " not found");
        }
    }
}
